package com.hannesdorfmann.mosby3.mvi;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.subjects.BehaviorSubject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class DisposableViewStateObserverTest {

    DisposableViewStateObserver disposableViewStateObserver;
    private String str;
    Throwable err;
    private boolean flag = false;
    Observable observable;

    @Before
    public void setUp() throws Exception {

        BehaviorSubject behaviorSubject = BehaviorSubject.create();
        disposableViewStateObserver = new DisposableViewStateObserver(behaviorSubject){

            @Override
            public void onNext(Object value) {
                super.onNext(value);
                str = (String) value;
            }

            @Override
            public void onError(Throwable e) {
                err = e;
            }

            @Override
            public void onComplete() {
                super.onComplete();
                flag = true;
            }
        };
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void onNext() {
        String test = "test onNext";
        str = null;
        observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext(test);
                e.onComplete();
            }
        });
        observable.subscribe(disposableViewStateObserver);
        assertEquals(str, test);
    }

    @Test
    public void onError() {
        err = null;
        Throwable throwable = new Throwable("test onError");
        observable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onError(throwable);
            }
        });
        observable.subscribe(disposableViewStateObserver);
        assertNotNull(err);
    }

    @Test
    public void onComplete() {
        flag = false;
        observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext("test onNext");
                e.onComplete();
            }
        });
        observable.subscribe(disposableViewStateObserver);
        assertTrue(flag);
    }
}